<template>
    <div class="three_page" id="threePage" >
    </div>
</template>
<script setup>
    import * as THREE from 'three'
    import {OrbitControls} from "three/addons/controls/OrbitControls.js";
    import {nextTick, onMounted} from "vue";
    import {GUI} from "three/addons/libs/lil-gui.module.min";
    import model from "@/js/model";
    import woman from "@/js/woman";
    let container
    let width
    let height
    let scene
    // let mesh
    let controls
    let camera
    //相机在z轴的位置
    // let zAixisNumber
    //相机
    let IMAGE_KEY=new URL('../assets/R.jpg',import.meta.url).href
    let IMAGE=new URL('../assets/G.jpg',import.meta.url).href
    let mesh2
    // 设置初始速度
    let speed = -0.04;
    //渲染器
    let renderer=null

    onMounted(()=> {
        container =document.getElementById('threePage')
        width=container.clientWidth
        height=container.clientHeight
        initScene()
        initSceneBG()
        initCamera()
        initRenderer()
        initOrbitControls()
        createLight()
        animate()

        // renderer.render(scene,camera)
        // console.log(scene,'环境')


    })
    function  createLight() {
        // 创建环境光
        let ambientLight = new THREE.AmbientLight('#fff', 1)
        ambientLight.decay = 2.0///光线衰弱，默认为2.0，不衰弱为0.0
        // ambientLight.position.set(0,1,1)
        let directionalLight = new THREE.DirectionalLight('#fff', 0.5);//创建一个方向光
        directionalLight.position.set(-60, 50, 10);
        scene.add(directionalLight);
        const light = new THREE.PointLight("#fff", 10,10,2);//点光源
        light.castShadow = true;//设置用于计算投影的光源对象
        light.shadow.camera.near = 2.1;
        light.shadow.camera.far = 300;
        light.position.set(-6, 2, 2);
        scene.add(light)
        // scene.add(ambientLight)
        // 创建一个圆形光晕的纹理
        const textureLoader = new THREE.TextureLoader();
        const spriteMap = textureLoader.load(IMAGE);
        const spriteMap1 = textureLoader.load(IMAGE_KEY);

        // 创建一个球体网格
        const sphereGeometry = new THREE.SphereGeometry(0.5, 68, 68);
        // const sphereMaterial = new THREE.MeshBasicMaterial({ color: 0xffffff,map:spriteMap });
        const sphereMaterial = new THREE.MeshPhongMaterial({
            color: 0xffffff,
            map:spriteMap1,
            emissive: 0xffffee,
            emissiveIntensity: 1,
            emissiveMap :spriteMap,
            shininess: 100
        });
        const sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);

        sphere.position.set(-6, 2, 1);
        sphere.rotateY(Math.PI/2);
        scene.add(sphere);

//
// // 创建一个SpriteMaterial来使用这个纹理
//         const spriteMaterial = new THREE.SpriteMaterial({ map: spriteMap, color: 0xffffff, blending: THREE.AdditiveBlending });
//         const sprite = new THREE.Sprite(spriteMaterial);
//         sprite.scale.set(1, 1, 1); // 调整这个来改变光晕的大小
//         sprite.position.copy(light.position); // 确保Sprite跟随PointLight的位置

// 将Sprite添加到场景中
//         scene.add(sprite);
        directionalLight.castShadow = true;//设置用于计算投影的光源对象
        directionalLight.shadow.camera.near = 2.1;
        directionalLight.shadow.camera.far = 300;
        directionalLight.shadow.camera.left = -50;
        directionalLight.shadow.camera.right = 150;
        directionalLight.shadow.camera.top = 100;
        directionalLight.shadow.camera.bottom = -150;

    }
    function shadowModel(data){
        nextTick(()=>{
            if (data) {
                data.traverse((child) => {
                    if (child instanceof THREE.Mesh) {
                        child.receiveShadow = true;//接受阴影
                        child.castShadow = true;//投射阴影
                    }
                });
            }
        })
    }
    //初始化场景
    function initScene(){
        scene = new THREE.Scene()
        scene.fog = new THREE.Fog(0x000000,1,1000)
        woman.position.set(-12,0,2)
        shadowModel(woman)
        shadowModel(model)
        scene.add(woman)
        scene.add(model)
    }
    //添加背景
    function initSceneBG(){
            //创建立方体
            let geometry = new THREE.BoxGeometry(2,2,2)
            let geometry1 = new THREE.BoxGeometry(2,2,2)
            let material1 = new THREE.MeshLambertMaterial({
                color:'#21c2c2'
            })
            mesh2 = new THREE.Mesh(geometry, material1);
            let mesh = new THREE.Mesh(geometry1, material1);
            mesh.position.set(-10,1,0)
            mesh2.position.set(0,1,0)
            mesh2.receiveShadow = true
            mesh.receiveShadow = true
            mesh2.castShadow = mesh2.receiveShadow = true;
            mesh.castShadow = mesh.receiveShadow = true;

        //辅助线条
            const axesHelper = new THREE.AxesHelper(50)
            scene.add(axesHelper)
            scene.add(mesh2)
        // scene.add(mesh)
        new THREE.TextureLoader().load(IMAGE_KEY,(texture)=> {
            let planeGeometry = new THREE.PlaneGeometry(300,200);//创建另一个几何体
            let planeMaterial = new THREE.MeshLambertMaterial({
                color:0x999999,
                map:texture,
                side:THREE.DoubleSide
            })
            let planMesh = new THREE.Mesh(planeGeometry,planeMaterial);//创建了一个平面模型
            planMesh.receiveShadow = true;//将他设置成接受投影效果
            scene.add(planMesh);//将这个模型添加到场景中
            planMesh.rotateX(-Math.PI/2);//旋转这个模型
            // planMesh.position.y = -20;//平移这个几何体
            // planMesh.position.z = 60;//平移这个几何体
        })
    }
    //初始化相机
    function initCamera(){
        //视野夹角
        let fov  =15
        //计算相机距离物体的距离
        // let distance = width/2/Math.tan(Math.PI/12)
        // zAixisNumber = Math.floor(distance - 1000/2)
        camera = new THREE.PerspectiveCamera(fov,width/height,1,2000)
        //设置相机的位置
        camera.position.set(100,200,5)
        //看向原点
        camera.lookAt(0,0,0)
    }
    //渲染器
    function initRenderer(){
        renderer= new THREE.WebGLRenderer({antialias:true})
        //定义渲染器的尺寸
        renderer.setSize(width,height)
        renderer.shadowMap.enabled =true//阴影
        renderer.setClearColor(0x444444, 1); //设置背景颜色
        renderer.shadowMap.type = THREE.PCFShadowMap
        container.appendChild(renderer.domElement)
    }


    //添加轨道控制器
    function initOrbitControls(){
        controls = new OrbitControls(camera,renderer.domElement)
        //设置阻力的惯性
        controls.enableDamping = true
        //设置阻力系数
        controls.dampingFactor = 0.05
        controls.autoRotate = true
        controls.enabled = true
        controls.update()
    }
    //动画刷新
    const animate=()=>{
        requestAnimationFrame(animate);
        // 更新立方体的旋转角度
        mesh2.rotation.x += 0.01;
        mesh2.rotation.y += 0.01;
        // 移动物体
        woman.position.x += speed;

        // 反转移动方向
        if (woman.position.x >= -10 || woman.position.x < -20) {
            speed = -speed;
        }
        resetShadow();
        renderer.render(scene,camera)
    }
//模型阴影重置
   function resetShadow(){
       shadowModel(woman)
       shadowModel(model)
    }
    window.addEventListener('resize',()=>{
        //重置渲染器宽高比
        renderer.setSize(width,height)
        //重置相机宽高比
        camera.aspect = width/height
        //更新相机投影矩阵
        camera.updateProjectionMatrix()
    })
    let eventObj={
        Fullscreen:function (){
            //全屏
            renderer.domElement.requestFullscreen()
        }
    }
    //创建GUI
    const gui = new GUI()
    //添加按钮
    gui.add(eventObj,'Fullscreen').name('全屏')

</script>


<style>
    .three_page {
        width: 100%;
        height: 100vh;
    }
    /*canvas{*/
    /*    display: block;*/
    /*    position: fixed;*/
    /*    left: 0;*/
    /*    top: 0;*/
    /*    width: 100vh;*/
    /*    height: 100vh;*/
    /*}*/
</style>
